package com.kamistoat.meimeichat.meimeichatclient.socket.handlers;

import com.kamistoat.meimeichat.meimeichatclient.application.UIServiceConnector;
import com.kamistoat.meimeichat.meimeichatclient.config.NettyClientConstant;
import com.kamistoat.meimeichat.meimeichatclient.infrastructure.util.CacheUtil;
import com.kamistoat.meimeichat.meimeichatclient.socket.NettyClientBizHandler;
import com.kamistoat.meimeichat.meimeichatui.view.chat.IChatMethod;
import com.kamistoat.meimeichatserveraggrement.protocol.login.ClientOnLineStatusNotice;
import io.netty.channel.Channel;
import javafx.application.Platform;

import java.net.InetSocketAddress;

/**
 * 某个Client的在线状态发生改变
 */
public class ClientOnLineStatusNoticeHandler extends NettyClientBizHandler<ClientOnLineStatusNotice> {
    public ClientOnLineStatusNoticeHandler(UIServiceConnector uiServiceConnector) {
        super(uiServiceConnector);
    }

    /**
     * Warning:子类只需要重写该方法
     *
     * @param channel
     * @param onLineStatusNotice
     */
    @Override
    public void channelRead(Channel channel, ClientOnLineStatusNotice onLineStatusNotice) {
        String friendId = onLineStatusNotice.getFriendId();
        Integer onLineStatus = onLineStatusNotice.getOnLineStatus();
        String onLineString = "";

        if(onLineStatus.equals(NettyClientConstant.OnLineStatus.OnLine.getCode())){
            onLineString = "[在线]";
            InetSocketAddress friendSocketAddress = new InetSocketAddress(
                    onLineStatusNotice.getClientAddressDto().getWantedUserHost(),
                    onLineStatusNotice.getClientAddressDto().getWantedUserPort());
            // 在线用户, 添加到 p2pMap 中记录地址
            CacheUtil.p2pMap.put(friendId, friendSocketAddress);
            logger.info("好友 {}, 最新状态: {}, 缓存好友UDP打洞地址: {}", friendId, onLineString, friendSocketAddress.toString());
        }else{
            onLineString = "[离线]";
            // 对于离线用户，从缓存记录中删除
            CacheUtil.p2pMap.remove(friendId);
            logger.info("好友 {}, 最新状态: {}, 删除好友UDP打洞地址", friendId, onLineString);
        }
        // 不管是在线还是离线，都要从P2PDate和P2PFailureDate中删除之前可能存在的链接记录，下次建立必然是重新建立
        CacheUtil.p2pDateMap.remove(friendId);
        CacheUtil.p2pFailureDateMap.remove(friendId);

        IChatMethod chat = uiServiceConnector.getIChatMethod();
        Platform.runLater(() -> {
            chat.changeFriendOnLineStatus(friendId, onLineStatus);
        });
    }
}
